package main

import (
	"du/config"
	"du/database"
	"du/middlewares"
	"du/models"
	"du/routes"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func main() {
	// 加载配置文件
	config.Load()

	// 初始化日志
	logger, err := zap.NewProduction()
	if err != nil {
		logger.Fatal("Failed to zap", zap.Error(err))
	}
	defer func(logger *zap.Logger) {
		err := logger.Sync()
		if err != nil {

		}
	}(logger)

	// 初始化数据库连接
	_, err = database.InitDB()
	if err != nil {
		logger.Fatal("Failed to init DB", zap.Error(err))
	}

	err = database.GetDB().GetMasterDB().AutoMigrate(models.User{})
	if err != nil {
		logger.Fatal("Failed to migrate table User", zap.Error(err))
		return
	}

	// 初始化Mongodb
	_, err = database.InitMongoDB()
	if err != nil {
		logger.Fatal("Failed to init Mongo DB", zap.Error(err))
	}

	// 初始化Redis
	_, err = database.InitRedisDB()
	if err != nil {
		logger.Fatal("Failed to init Redis DB", zap.Error(err))
	}

	// 初始化 Gin 引擎
	engine := gin.Default()
	engine.SetTrustedProxies(nil)

	// engine.Use(gin.Logger())
	engine.Use(gin.Recovery())
	engine.Use(middlewares.Logger(logger))
	engine.Use(middlewares.Authentication())

	// 注册路由
	routes.RegisterRoutes(engine)

	logger.Info("Server started", zap.String("address", config.App.App.Port))

	// 启动服务
	err = engine.Run(config.App.App.Port)

	if err != nil {
		logger.Fatal("Failed to start server", zap.Error(err))
	}
}
